package net.kts.story.twitter.oauth;

import net.kts.story.twitter.store.TwitterTokenStore;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

public class OAuth {
	private static final String CONSUMER_KEY = "42VuKm76XmCvAfp02hfA";
	private static final String CONSUMER_SECRET = "DM7Dxqle5cVog2iVrwt25C69bQHqG6vo5R4sowlFo";
	private static final String ACCSSE_TOKEN = "125049216-UsiyYOtzANijjvm3r1jl4JzKVZMr5ObYld1XGrW0";
	private static final String ACCESS_TOKEN_SECRET = "CTJiehfL5FK3BC5TRj2DOpBqHglGcvUj3J4DlIxE";
	private static Uri TWITTER_CALLBACK_URL = Uri.parse("KoreaTravelTest://twitter");
	private RequestToken requestToken;
	private TwitterTokenStore twitterTokenStore;
	private AccessToken accessToken;
	private Activity activity;
	private Twitter twitter;
	
	public OAuth(Activity activity) {
		super();
		this.activity = activity;
		this.twitterTokenStore = new TwitterTokenStore(activity);
		Log.d("Twitter", "OAuth created");
	}

	public Twitter findTwitter() throws TwitterException {
		twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
		requestToken = twitter.getOAuthRequestToken();
		return twitter;
	}

	public boolean authMemberInformation() throws TwitterException {
		accessToken = twitterTokenStore.findAccessToken();
//		requestToken = twitter.getOAuthRequestToken();
		
		if(accessToken != null){
			Log.d("Twitter", "OAuth accesssTorken set");
			twitter.setOAuthAccessToken(accessToken);
			return true;
		}
		if (accessToken == null){
			Log.d("Twitter", "OAuth call to TwitterOAuthActivity");
			Log.d("Twitter", activity.toString());
			Intent intent = new Intent(activity, TwitterOAuthActivity.class);
			intent.putExtra("URL", requestToken.getAuthorizationURL());
			activity.startActivityForResult(intent, 1);
			Log.d("Twitter", "OAuth called to TwitterOAuthActivity");
		}
		return false;
	}

	public void obtainCertification(String pin) {
		try {
			Log.d("Twitter", "OAuth obtationCertification pin : "+pin);
			accessToken = twitter.getOAuthAccessToken(requestToken, pin);
			twitterTokenStore.storeToken(accessToken);
			twitter.setOAuthAccessToken(accessToken);
			Log.d("Twitter", "OAuth obtationCertification accessToken : "+accessToken.toString());
		} catch (TwitterException te) {
			Log.e("twitter", te.getMessage());
		}
	}
}
